package tv.youxing.android;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import tv.youxing.android.adapter.AlbumVideoBatchDownloadAllManagerAdapter;
import tv.youxing.android.adapter.Download_AllManager_Adapter;
import tv.youxing.android.custom.CustomToast;
import tv.youxing.android.entity.AlbumVideoBatchDownloadsModel;
import tv.youxing.android.entity.DownloadInfoModel;
import tv.youxing.android.ui.BaseActivity;
import tv.youxing.android.ui.LoginActivity;
import tv.youxing.android.ui.test.DownloadAdapter;
import tv.youxing.android.ui.test.test3DownloadListener;
import tv.youxing.android.utils.AppConst;
import tv.youxing.android.utils.UtilTools;

import static tv.youxing.android.R.id.recyclerView;


/**
 * 专辑详情 -> 批量下载
 * */
public class AlbumVideoBatchDownloadsActivity extends BaseActivity {


    TextView VideoCount;//集数
    ListView mListView;
    GridView mGridView;
    Button btn_download;
    private List<AlbumVideoBatchDownloadsModel> mListDatas;//可下载的节目
    private ArrayList<Integer> mDownloadIds = new ArrayList<>();//要下载的节目ID
    private ArrayList<AlbumVideoBatchDownloadsModel> mDownloadsURLs = new ArrayList<>();//要下载的节目url
    private Adapter mAdapter;




    AlbumVideoBatchDownloadAllManagerAdapter new_adapter;
RecyclerView mRecyclerView;

    Download_AllManager_Adapter adapter;

    //全局下载文件管理器
    OkDownload okDownload;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_album_video_batch_downloads);


        VideoCount = (TextView) findViewById(R.id.tvEpisode);
//        mListView = (ListView) findViewById(R.id.lv_batch_download);
        btn_download = (Button) findViewById(R.id.btn_download);
        mRecyclerView = (RecyclerView) findViewById(recyclerView);

        mListDatas = (List<AlbumVideoBatchDownloadsModel>) getIntent().getSerializableExtra("data");


        mGridView = (GridView) findViewById(R.id.lv);
        okDownload = OkDownload.getInstance();

////        for (int i = 0; i < mListDatas.size(); i++) {
////            new_adapter.add(mListDatas.get(i).getPlay_url());
////        }
//        new_adapter = new AlbumVideoBatchDownloadAllManagerAdapter(this);
//        new_adapter.updateData(Download_AllManager_Adapter.TYPE_ALL);
//        mGridView.setAdapter(new_adapter);
//        mListView.setAdapter(new_adapter);




        new_adapter = new AlbumVideoBatchDownloadAllManagerAdapter(this,this,mListDatas);
        new_adapter.updateData(DownloadAdapter.TYPE_ALL);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//        recyclerView.setLayoutManager(new GridLayoutManager(this,2));
        mRecyclerView.setAdapter(new_adapter);



        VideoCount.setText("共 "+mListDatas.size()+" 集");

//        adapter = new Download_AllManager_Adapter(this);
//        adapter.updateData(Download_AllManager_Adapter.TYPE_ALL);


//        mAdapter = new Adapter(this, mListDatas);
//        mGridView.setAdapter(mAdapter);
//        mListView.setAdapter(adapter);


//        mListView.setAdapter(mAdapter);

        btn_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (mDownloadsURLs.size() == 0) {
                    CustomToast.INSTANCE.showToast("请添加下载任务");
                    return;
                }


                for (int i = 0; i < mDownloadsURLs.size(); i++) {

//                    System.out.println(mDownloadsURLs.get(i).getPlay_url());

//                    //开始下载 相同的下载地址只会下载一个
                    DownloadInfoModel model = new DownloadInfoModel();
                    model.url = mDownloadsURLs.get(i).getPlay_url();
//                    model.url = "http://video.jiecao.fm/11/23/xin/%E5%81%87%E4%BA%BA.mp4";
                    model.iconUrl = mDownloadsURLs.get(i).getIcon_url();
                    model.name = mDownloadsURLs.get(i).getTitle();
                    videoDownload(model);

//                    //更新界面
                    mAdapter.notifyDataSetChanged();
                }

                //专辑详情 -> 节目
                EventBus.getDefault().post(AppConst.dynamic_program_Refresh);

                finish();
                CustomToast.INSTANCE.showToast("开始下载");
            }
        });
    }



    private void videoDownload(DownloadInfoModel model) {
        if (!UtilTools.LoginJudge()) {
            startActivity(new Intent(this,LoginActivity.class));
            return;
        }

        if (model == null) {
            System.out.println("数据null");
            return;
        }

        DownloadInfoModel apk = model;


//        if (OkDownload.getInstance().getTask(apk.url) != null) {
////            tvDownload.setText("已下载");
////            tvDownload.setEnabled(false);
//        } else {
////            tvDownload.setText("下载");
////            tvDownload.setEnabled(true);
//        }


        GetRequest<File> request = OkGo.<File>get(apk.url);//
//                .headers("aaa", "111")//
//                .params("bbb", "222");

        //这里第一个参数是tag，代表下载任务的唯一标识，传任意字符串都行，需要保证唯一,我这里用url作为了tag
        OkDownload.request(apk.url, request)//
                .priority(apk.priority)//
                .extra1(apk)//
                .save()
                .register(new test3DownloadListener())//
                .start();
    }



    class Adapter extends BaseAdapter {


        private Context context;
        private List<AlbumVideoBatchDownloadsModel> videoModelList = new ArrayList<>();
        private LayoutInflater layoutInflater;

        public Adapter(Context context, List<AlbumVideoBatchDownloadsModel> videoModelList) {
            this.context = context;
            this.videoModelList = videoModelList;
            layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        }


        @Override
        public int getCount() {
            return videoModelList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (viewHolder==null) {
                viewHolder = new ViewHolder();
                convertView = layoutInflater.inflate(R.layout.albumvideo_batch_downloads_item, null);
                viewHolder.rootView = convertView.findViewById(R.id.rootView);
                viewHolder.tvTitle = convertView.findViewById(R.id.title);
                viewHolder.ivDownloadIcon = convertView.findViewById(R.id.iv_icon);
                convertView.setTag(viewHolder);
            }else{
                viewHolder = (ViewHolder) convertView.getTag();
            }


            viewHolder.tvTitle.setText(videoModelList.get(position).getTitle());


            DownloadTask task = OkDownload.getInstance().getTask(videoModelList.get(position).getPlay_url());



            if (task != null) {
                String holderTag = task.progress.tag;
                task.register(new ListDownloadListener(holderTag, viewHolder));
                viewHolder.setTag(holderTag);
                viewHolder.setTask(task);
                viewHolder.bind();
                viewHolder.refresh(task.progress);
            } else {
                viewHolder.ivDownloadIcon.setSelected(false);
                viewHolder.ivDownloadIcon.setEnabled(true);
            }




//            if (task != null) {
//                viewHolder.ivDownloadIcon.setSelected(true);
//                viewHolder.ivDownloadIcon.setEnabled(false);
//            } else {
//                viewHolder.ivDownloadIcon.setSelected(false);
//                viewHolder.ivDownloadIcon.setEnabled(true);
//            }

            final ViewHolder finalViewHolder = viewHolder;
            viewHolder.ivDownloadIcon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (finalViewHolder.ivDownloadIcon.isSelected()) {
                        finalViewHolder.ivDownloadIcon.setSelected(false);
                        addDownloadTasks(false,videoModelList.get(position).getMultimedia_id(),videoModelList.get(position));
                    } else {
                        finalViewHolder.ivDownloadIcon.setSelected(true);
                        addDownloadTasks(true,videoModelList.get(position).getMultimedia_id(),videoModelList.get(position));
                    }
                }
            });

            return convertView;
        }



    }


    class ViewHolder{
        private RelativeLayout rootView;
        private TextView tvTitle;
        private ImageView ivDownloadIcon;//下载图标
        boolean isRef=true;


        private DownloadTask task;
        String tag;


        public String getTag() {
            return tag;
        }

        public void setTag(String tag) {
            this.tag = tag;
        }

        public void setTask(DownloadTask task) {
            this.task = task;
        }

        public void bind() {
            Progress progress = task.progress;

            switch (progress.status) {
                case Progress.PAUSE:
                case Progress.NONE:
                case Progress.ERROR:
                    ivDownloadIcon.setSelected(false);
                    ivDownloadIcon.setEnabled(true);
                    break;
                case Progress.LOADING:
                    break;
                case Progress.FINISH:
                    ivDownloadIcon.setSelected(true);
                    ivDownloadIcon.setEnabled(false);
                    break;
            }


            rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    dialog2();

                    isRef=false;

                }
            });


        }

        //适配操作的dialog
        private void dialog2() {
            isRef=false;
            final String items[]={"开始","删除","重新下载"};
            //dialog参数设置
            AlertDialog.Builder builder=new AlertDialog.Builder(getApplicationContext());  //先得到构造器
//            builder.setTitle("提示"); //设置标题
            //builder.setMessage("是否确认退出?"); //设置内容
            builder.setIcon(R.mipmap.ic_launcher);//设置图标，图片id即可
            //设置列表显示，注意设置了列表显示就不要设置builder.setMessage()了，否则列表不起作用。
            builder.setItems(items,new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    if (items[which].equals("开始")) {
                    } else if (items[which].equals("删除")) {
                    } else if (items[which].equals("重新下载")) {
                    }

                }
            });
            builder.setPositiveButton("关闭",new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.create().show();

            builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialogInterface) {
//                    isRef=true;
                }
            });
        }


        public void refresh(Progress progress) {
            String currentSize = Formatter.formatFileSize(getApplicationContext(), progress.currentSize);
            String totalSize = Formatter.formatFileSize(getApplicationContext(), progress.totalSize);
            switch (progress.status) {
                case Progress.NONE:
                    tvTitle.setText("停止");
                    break;
                case Progress.PAUSE:
                    tvTitle.setText("继续");
                    break;
                case Progress.ERROR:
                    tvTitle.setText("出错");
                    break;
                case Progress.WAITING:
                    tvTitle.setText("等待");
                    break;
                case Progress.FINISH:
//                    if (ApkUtils.isAvailable(context, new File(progress.filePath))) {
//                        download.setText("卸载");
//                    } else {
//                        download.setText("安装");
//                    }
                    tvTitle.setText("下载完成");
                    break;
                case Progress.LOADING:
                    String speed = Formatter.formatFileSize(getApplicationContext(), progress.speed);
                    tvTitle.setText(String.format("%s/s", speed));

//                    if (isRef) {
//                        mAdapter.notifyDataSetChanged();
//                    }
                    System.out.println("speed:" + speed);
                    break;
            }
            //进度条
//                tvProgress.setText(numberFormat.format(progress.fraction));
//                pbProgress.setMax(10000);
//                pbProgress.setProgress((int) (progress.fraction * 10000));
        }

    }


    //添加下载任务
    void addDownloadTasks(boolean is_selected,int multimedia_id,AlbumVideoBatchDownloadsModel albumVideoBatchDownloadsModel) {
        if (is_selected) {
            mDownloadIds.add(multimedia_id);
            mDownloadsURLs.add(albumVideoBatchDownloadsModel);


        }else{
            for (int i = 0; i < mDownloadIds.size(); i++) {
                if (mDownloadIds.get(i) == multimedia_id) {
                    mDownloadIds.remove(i);
                }
            }
            for (int i = 0; i < mDownloadsURLs.size(); i++) {
                if (mDownloadsURLs.get(i) == albumVideoBatchDownloadsModel) {
                    mDownloadsURLs.remove(i);
                }
            }
        }
    }


    //开始下载
    void download() {
        };


    private class ListDownloadListener extends DownloadListener {

        private ViewHolder holder;

        ListDownloadListener(Object tag, ViewHolder holder) {
            super(tag);
            this.holder = holder;
        }

        @Override
        public void onStart(Progress progress) {
        }

        @Override
        public void onProgress(Progress progress) {



            if (tag == holder.getTag()) {
                holder.refresh(progress);
                System.out.println("2:progress");
            }
        }

        @Override
        public void onError(Progress progress) {
            Throwable throwable = progress.exception;
            if (throwable != null) throwable.printStackTrace();
        }

        @Override
        public void onFinish(File file, Progress progress) {
//            Toast.makeText(context, "下载完成:" + progress.filePath, Toast.LENGTH_SHORT).show();
           // updateData(type);
        }

        @Override
        public void onRemove(Progress progress) {
        }
    }


}
